import { ELanguageType, ITransOption } from "./common/Types";
import LanguageUtils from "./utils/LanguageUtils";

const App = CS.FairyEditor.App;

/**
 * 插件App
 */
export default class ToolPlugin {
    private static _instance: ToolPlugin | undefined;
    private _rootPath: string = "";
    private _i18Path: string = "";

    public static get instance(): ToolPlugin {
        if (!ToolPlugin._instance) {
            ToolPlugin._instance = new ToolPlugin();
            ToolPlugin._instance.init();
        }

        return ToolPlugin._instance;
    }

    public static destroy() {
        if (ToolPlugin._instance) {
            ToolPlugin._instance.cleanup();
            ToolPlugin._instance = undefined;
        }
    }

    public init() {
        console.log("===>ToolPlugin::init");
        this._rootPath = App.pluginManager.basePath + "/" + ToolPlugin.name;
        this._i18Path = App.project.basePath + "/i18";

        // 加载插件UI资源包
        console.log("===>load plugin pkg from " + this._rootPath);
        // App.pluginManager.LoadUIPackage(this._rootPath + "/res/Basic")
        // App.pluginManager.LoadUIPackage(this._rootPath + "/res/Builder")

        this.loadMenu();
    }

    private loadMenu() {
        const toolmenu = App.menu.GetSubMenu("tool");
        toolmenu.AddItem("简体转繁体", "transCN2TW", this.transCN2TW.bind(this));
        toolmenu.AddItem("资源统计", "analyzeRes", this.analyzeRes.bind(this));
    }

    /**
     * 简体转繁体
     */
    private transCN2TW() {
        console.log(`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`);
        console.log("开始导出...");

        const cnFilePath = this._i18Path + "/strings_zh-Hans.xml";
        const twFilePath = this._i18Path + "/strings_zh-Hant.xml";
        const xmlContent = CS.System.IO.File.ReadAllText(cnFilePath);

        // 1. 生成繁体中文 (zh-TW)
        const param: ITransOption = {
            text: xmlContent,
            from: ELanguageType.CN,
            to: ELanguageType.TW,
        };
        const twXml = LanguageUtils.transZH(param);
        CS.System.IO.File.WriteAllText(twFilePath, twXml);

        console.log("多语言文件导出完成！");
        console.log(`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`);
    }

    /**
     * 资源统计

     */
    private analyzeRes() {
        console.log(`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`);

        const activeItem = App.GetActiveFolder();
        const curBranch = activeItem.branch;
        const activePkg = App.project.GetPackageByName(activeItem.owner.name);
        const activePkgName = activePkg.name;
        console.log(`========= 统计资源 [${activePkgName}] =========`);

        let totalSize = 0;
        let exportedSize = 0;
        let unusedSize = 0;
        const resTypeMap = new Map();
        const itemMap = new Map();

        for (let idx = 0; idx < activePkg.items.Count; idx++) {
            const item = activePkg.items.get_Item(idx);
            if (item.branch == curBranch && item.type != "folder") {
                itemMap.set(item.id, { item, used: item.exported });
                resTypeMap.set(item.type, (resTypeMap.get(item.type) || 0) + 1);

                totalSize += 1;
                if (item.exported) {
                    exportedSize += 1;
                }
            }
        }

        for (let [key, value] of itemMap) {
            const { item } = value;
            const query = new CS.FairyEditor.DependencyQuery();
            query.QueryDependencies(App.project, item.GetURL(), CS.FairyEditor.DependencyQuery.SeekLevel.ALL);
            query.resultList.ForEach(ref => {
                if (itemMap.get(ref.item.id)) {
                    itemMap.get(ref.item.id).used = true;
                }
            });
        }

        console.log(`=== 【资源总数】: ${totalSize}`);
        console.log(`=== 【资源类型】:`);
        for (let [key, value] of resTypeMap) {
            console.log(` [${key}]: ${value} 个`);
        }
        console.log(`=== 【已导出】: ${exportedSize}, 【未导出】: ${totalSize - exportedSize}`);
        console.log(`=== 【未使用资源】:`);
        for (let [key, value] of itemMap) {
            if (!value.used) {
                unusedSize += 1;
                console.log(` [${value.item.type}]: ${value.item.path}${value.item.name} `);
            }
        }
        console.log(`=== 【未使用总计】: ${unusedSize}`);

        console.log(`=========统计结束=========`);
        console.log(`~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`);
    }

    public cleanup() {
        let toolmenu = App.menu.GetSubMenu("tool");
        toolmenu.RemoveItem("transCN2TW");
        toolmenu.RemoveItem("analyzeRes");
        App.consoleView.Log("插件卸载");
    }
}
